<template>
    <div>
        <a-form layout="inline"
                :model="searchData"
                style="margin: 10px 0">
            <a-form-item>
                <a-input v-model:value="searchData.name" placeholder="模板名称"></a-input>
            </a-form-item>
            <a-form-item>
                <a-input v-model:value="searchData.brandIds" placeholder="关联品牌"></a-input>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="load">搜索</a-button>
            </a-form-item>
            <a-form-item>
                <a-button type="default" @click="rest">重置</a-button>
            </a-form-item>
        </a-form>
        <a-button type="primary" style="margin-bottom: 10px" @click="openModal({})">新增</a-button>
        <a-table :dataSource="templateList"
                 :columns="columns"
                 :pagination="pagination"
                 @change="handlerChange"
                 bordered>
            <template #specIds="{text,record}">
                {{jsonToString(text,'text')}}
            </template>
            <template #brandIds="{text,record}">
                {{jsonToString(text,'text')}}
            </template>
            <template #customAttributeItems="{text,record}">
                {{jsonToString(text,'text')}}
            </template>
            <template #action="{text,record}">
                <a-button type="primary" @click="openModal(record)">编辑</a-button>
                <a-popconfirm
                        title="删除数据无法恢复，请确认是否删除？"
                        ok-text="是"
                        cancel-text="否"
                        @confirm="okDelete(record.id)"
                >
                    <a-button type="danger">删除</a-button>
                </a-popconfirm>
            </template>
        </a-table>
        <a-modal v-model:visible="visible" title="新增或编辑" @ok="handleOk">
            <a-form v-model="templateGroup"
                    :label-col="{ span: 8 }">
                <a-form-item label="模板名称">
                    <a-input v-model:value="templateGroup.name"></a-input>
                </a-form-item>
                <a-form-item label="关联规格">
                    <a-select
                            v-model:value="templateGroup.specIds"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="Please select"
                            :options="specificationList"
                            :field-names="{label:'specName',value:'id'}"
                            :labelInValue="true">
                    </a-select>
                </a-form-item>
                <a-form-item label="关联品牌">
                    <a-select
                            v-model:value="templateGroup.brandIds"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="Please select"
                            :options="brandList"
                            :field-names="{label:'name',value:'id'}"
                            :labelInValue="true">
                    </a-select>
                </a-form-item>
                <a-form-item label="扩展属性">
                    <a-button type="primary" @click="addAttributeOption">新增扩展属性</a-button>
                    <table width="100%" border="1">
                        <thead>
                        <td>扩展属性</td>
                        <td>操作</td>
                        </thead>
                        <tbody>
                        <tr v-for="(item,index) in templateGroup.customAttributeItems" :key="index">
                            <td>
                                <a-input v-model:value="item.text"></a-input>
                            </td>
                            <td>
                                <a-button type="danger" @click="delAttributeOption(index)">删除</a-button>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import {message} from 'ant-design-vue'
    import axios from 'axios'

    export default {
        name: "admin-templates",
        setup() {
            const columns = [
                {
                    title: '模板ID',
                    dataIndex: 'id',
                    key: 'id',
                    align: 'center',
                    width: '8%'
                },
                {
                    title: '模板名称',
                    dataIndex: 'name',
                    key: 'name',
                    align: 'center',
                    width: '8%'
                },
                {
                    title: '关联规格',
                    dataIndex: 'specIds',
                    key: 'specIds',
                    align: 'center',
                    slots: {customRender: 'specIds'}
                },
                {
                    title: '关联品牌',
                    dataIndex: 'brandIds',
                    key: 'brandIds',
                    align: 'center',
                    slots: {customRender: 'brandIds'}
                },
                {
                    title: '扩展属性',
                    dataIndex: 'customAttributeItems',
                    key: 'customAttributeItems',
                    align: 'center',
                    slots: {customRender: 'customAttributeItems'}
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    slots: {customRender: 'action'},
                    width: '16%'
                },
            ]

            const searchData = ref({})
            const templateGroup = ref({})
            const templateList = ref()
            const brandList = ref([])
            const specificationList = ref([])
            const visible = ref(false)
            const pagination = ref({
                current: 1,
                pageSize: 10
            })

            const load = () => {
                axios.get('/mall-manager/template/list', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        name: searchData.value.name,
                        brandIds: searchData.value.brandIds
                    }
                }).then(rs => {
                    console.log("查找的结果：", rs)
                    templateList.value = rs.data.data.list
                    pagination.value.total = rs.data.data.total
                })
            }

            const handlerChange = (pageInfo) => {
                pagination.value = pageInfo
                load()
            }

            const jsonToString = (json, parameter) => {
                let objs = JSON.parse(json)
                let rs = ""
                objs.forEach((val, index) => {
                    rs += index == objs.length - 1 ? val[parameter] : (val[parameter] + "，")
                })
                return rs
            }

            const rest = () => {
                searchData.value = {}
                load()
            }

            const openModal = (obj) => {
                visible.value = true
                templateGroup.value = JSON.parse(JSON.stringify(obj))
                if (JSON.stringify(obj) != '{}') {
                    let brandIds = JSON.parse(templateGroup.value.brandIds)
                    let specIds = JSON.parse(templateGroup.value.specIds)
                    templateGroup.value.brandIds = objToOptions(brandIds, 'id', 'text')
                    templateGroup.value.specIds = objToOptions(specIds, 'id', 'text')
                    templateGroup.value.customAttributeItems = JSON.parse(templateGroup.value.customAttributeItems)
                } else {
                    templateGroup.value.customAttributeItems = []
                }
            }

            const handleOk = () => {
                console.log("提交的数据", templateGroup)
                let template = {}
                template.id = templateGroup.value.id
                template.name = templateGroup.value.name
                template.customAttributeItems = JSON.stringify(templateGroup.value.customAttributeItems)
                template.brandIds = []
                templateGroup.value.brandIds.forEach((val) => {
                    template.brandIds.push({
                        id: val.value,
                        text: val.label
                    })
                })
                template.brandIds = JSON.stringify(template.brandIds)
                template.specIds = []
                templateGroup.value.specIds.forEach((val) => {
                    template.specIds.push({
                        id: val.value,
                        text: val.label
                    })
                })
                template.specIds = JSON.stringify(template.specIds)

                axios.post('/mall-manager/template/saveOrUpdate', template).then(rs => {
                    console.log("新增或编辑结果：", rs)
                    if (rs.data.code == 200){
                        message.success("操作成功")
                        visible.value = false
                        load()
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            const okDelete = (id) =>{
                axios.delete('/mall-manager/template/delete/' + id).then(rs=>{
                    console.log("新增或编辑结果：", rs)
                    if (rs.data.code == 200){
                        message.success("操作成功")
                        load()
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            const objToOptions = (obj, valName, labelName) => {
                let rs = []
                obj.forEach((val, index) => {
                    rs.push({
                        label: val[labelName],
                        value: val[valName]
                    })
                })
                return rs
            }

            const addAttributeOption = () => {
                templateGroup.value.customAttributeItems.push({})
            }

            const delAttributeOption = (index) => {
                templateGroup.value.customAttributeItems.splice(index, 1)
            }

            onMounted(() => {
                load()
                axios.get('/mall-manager/brand/queryAll').then(rs => {
                    console.log("全部品牌：", rs)
                    brandList.value = rs.data.data
                })
                axios.get('/mall-manager/specification/queryAll').then(rs => {
                    console.log("全部规格：", rs)
                    specificationList.value = rs.data.data
                })
            })

            return {
                columns,
                searchData,
                templateList,
                pagination,
                load,
                handlerChange,
                jsonToString,
                rest,
                visible,
                openModal,
                templateGroup,
                brandList,
                specificationList,
                addAttributeOption,
                delAttributeOption,
                handleOk,
                okDelete
            }
        }
    }
</script>

<style scoped>

</style>